package 书店销售管理系统;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

import javax.swing.*;
import javax.swing.table.*;

public class UserManagement extends JFrame {
    private static final long serialVersionUID = 1L;
    private JTable table;
    private DefaultTableModel model;

    private final String url = "jdbc:oracle:thin:@localhost:1521:xe";
    private final String user = "HR";
    private final String password = "123456";

    public UserManagement() {
        setTitle("用户信息管理");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900, 700);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 设置背景
        JPanel background = new JPanel() {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // 绘制半透明粉色背景
                g.setColor(new Color(255, 192, 203, 128));
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        add(background, BorderLayout.CENTER);
        // 创建顶部面板
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        topPanel.setOpaque(false); // 设置为透明背景

        // 添加菜单栏
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        // 添加下拉菜单
        JMenu dropDownMenu = new JMenu("菜单");
        menuBar.add(dropDownMenu);

        // 添加子菜单：销售信息管理
        JMenuItem salesItem = new JMenuItem("销售信息管理");
        salesItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“销售信息管理”界面的代码
                new SalesManagement().setVisible(true);
            }
        });
        dropDownMenu.add(salesItem);

        // 添加子菜单：图书信息管理
        JMenuItem bookItem = new JMenuItem("图书信息管理");
        bookItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“图书信息管理”界面的代码
                new Book().setVisible(true);
            }
        });
        dropDownMenu.add(bookItem);
        
        // 添加子菜单：会员信息管理
        JMenuItem memberItem = new JMenuItem("会员信息管理");
        memberItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“会员信息管理”界面的代码
                new MemberManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem);
         
        // 添加子菜单：会员类别管理
        JMenuItem memberItem1 = new JMenuItem("会员类别管理");
        memberItem1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“会员类别管理”界面的代码
                new VipTypeManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem1);

        // 添加子菜单：退出
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭窗口
                System.exit(0); // 退出应用程序
            }
        });
        dropDownMenu.add(exitItem);

        // 添加按钮：添加、编辑、删除、查询
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UserDialog dialog = new UserDialog(UserManagement.this, "Add User", null);
                if (dialog.isOK()) {
                    addUser(dialog.getData());
                }
            }
        });
        topPanel.add(addButton);

        JButton editButton = new JButton("Edit");
        editButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    String username = (String) model.getValueAt(row, 0);
                    Object[] data = { username, model.getValueAt(row, 1) };
                    UserDialog dialog = new UserDialog(UserManagement.this, "Edit User", data);
                    if (dialog.isOK()) {
                        editUser(dialog.getData());
                    }
                } else {
                    JOptionPane.showMessageDialog(UserManagement.this, "Please select a user to edit.");
                }
            }
        });
        topPanel.add(editButton);

        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    String uno = (String) model.getValueAt(row, 0);
                    int result = JOptionPane.showConfirmDialog(UserManagement.this,
                            "Are you sure you want to delete user \"" + uno + "\"?", "Delete User",
                            JOptionPane.YES_NO_OPTION);
                    if (result == JOptionPane.YES_OPTION) {
                        deleteUser(uno);
                    }
                } else {
                    JOptionPane.showMessageDialog(UserManagement.this, "Please select a user to delete.");
                }
            }
        });
        topPanel.add(deleteButton);

        JTextField searchField = new JTextField(20);
        searchField.setHorizontalAlignment(JTextField.CENTER); // 设置文本框居中对齐
        searchField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchUser(searchField.getText());
            }
        });
        topPanel.add(searchField);

        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchUser(searchField.getText());
            }
        });
        topPanel.add(searchButton);

        // 添加顶部面板
        background.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = { "用户名", "密码" };
        model = new DefaultTableModel(columnNames, 0);
        table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);
        table.setPreferredScrollableViewportSize(new Dimension(600, 400));

        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        background.add(scrollPane, BorderLayout.CENTER);

        refreshTable(); // 刷新表格
        setVisible(true);
    }

    private void refreshTable() {
        model.setRowCount(0); // 清空表格数据
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM USER1");
            while (rs.next()) {
                String username = rs.getString("UNO");
                String password = rs.getString("PASSWORD");
                model.addRow(new Object[] { username, password });
            }
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void addUser(Object[] data) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn
                    .prepareStatement("INSERT INTO USER1 (UNO, PASSWORD) VALUES (?, ?)");
            pstmt.setString(1, data[0].toString());
            pstmt.setString(2, data[1].toString());
            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 添加成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void editUser(Object[] data) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn.prepareStatement(
                    "UPDATE USER1 SET PASSWORD = ? WHERE UNO = ?");
            pstmt.setString(1, data[1].toString());
            pstmt.setString(2, data[0].toString());

            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 修改成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void deleteUser(String username) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn.prepareStatement("DELETE FROM USER1 WHERE UNO = ?");
            pstmt.setString(1, username);
            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 删除成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void searchUser(String keyword) {
        model.setRowCount(0); // 清空表格数据
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(
                    "SELECT * FROM USER1 WHERE UPPER(UNO) LIKE '%" + keyword.toUpperCase() + "%'");
            while (rs.next()) {
                String username = rs.getString("UNO");
                String password = rs.getString("PASSWORD");
                model.addRow(new Object[] { username, password });
            }
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace(); } }

private class UserDialog extends JDialog {
    private static final long serialVersionUID = 1L;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private boolean isOK;

    public UserDialog(JFrame parent, String title, Object[] data) {
        super(parent, title, true); // 模态对话框
        setSize(300, 200);
        setLocationRelativeTo(null);
        setResizable(false);
        setLayout(new BorderLayout());

        JPanel panel = new JPanel(new GridLayout(2, 2, 5, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JLabel usernameLabel = new JLabel("UNO:");
        panel.add(usernameLabel);

        usernameField = new JTextField();
        panel.add(usernameField);

        JLabel passwordLabel = new JLabel("Password:");
        panel.add(passwordLabel);

        passwordField = new JPasswordField();
        panel.add(passwordField);

        add(panel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                isOK = true;
                dispose();
            }
        });
        buttonPanel.add(okButton);

        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        buttonPanel.add(cancelButton);

        add(buttonPanel, BorderLayout.SOUTH);

        if (data != null) {
            usernameField.setText(data[0].toString());
            passwordField.setText(data[1].toString());
        }
        setVisible(true);
    }

    public boolean isOK() {
        return isOK;
    }

    public Object[] getData() {
        Object[] data = { usernameField.getText(), new String(passwordField.getPassword()) };
        return data;
    }
}
public static void main(String[] args) {
    new UserManagement();
}
}
